package com.jingyanzi.member.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.member.api.DicClientAPI;
import com.jingyanzi.member.dao.MCustomerFamilyMapper;
import com.jingyanzi.member.domain.CustomerFamilyDO;
import com.jingyanzi.member.domain.result.ResultDO;
import com.jingyanzi.member.domain.result.ResultSupport;
import com.jingyanzi.member.entity.MCustomerFamily;
import com.jingyanzi.member.entity.MCustomerFamilyExample;
import com.jingyanzi.member.entity.MCustomerFamilyExample.Criteria;
import com.jingyanzi.member.query.CustomerFamilyQueryDO;
import com.jingyanzi.member.service.ICustomerFamilyService;
import com.jingyanzi.member.util.BeanUtilsExtends;
import com.jingyanzi.member.util.MemberConstant;
import com.jingyanzi.sys.domain.DictionariesDO;

@Service("customerFamilyService")
public class CustomerFamilyServiceImpl extends BaseServiceImpl implements ICustomerFamilyService {

	private static Logger logger = Logger.getLogger(CustomerFamilyServiceImpl.class);

	@Autowired
	private MCustomerFamilyMapper customerFamilyMapper;

	@Autowired
	private DicClientAPI dicClientAPI;

	@Override
	public ResultDO add(CustomerFamilyDO domain) {

		MCustomerFamily entity = new MCustomerFamily();
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		if (!result.isSuccess()) {
			result.setErrorMsg("插入客户家庭联系人错误对象复制错误");
			return result;
		}
		entity.setCreatetime(Calendar.getInstance().getTime());
		entity.setModifitime(entity.getCreatetime());
		entity.setIsDelete(MemberConstant.DB_ISDEL_NO);
		if (StringUtils.isNotEmpty(domain.getBirthdayStamp())) {
			entity.setBirthday(new Date(Long.parseLong(domain.getBirthdayStamp())));
		}
		if (domain.getIsFirst() == null) {
			entity.setIsFirst(MemberConstant.FAMILY_IS_OTHER);
		}
		int ret = -1;

		try {
			ret = customerFamilyMapper.insertSelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			ret = -1;
		}

		if (ret < 0) {
			result.setErrorMsg("插入客户家庭联系人错误插入失败");
			result.setSuccess(false);
		}

		return result;
	}

	@Override
	public ResultDO checkMobileNumber(CustomerFamilyDO domain) {

		ResultSupport result = new ResultSupport();
		// 验证手机号是否有效
		if (!isChinaPhoneLegal(domain.getTelephone())) {
			result.setErrorCode(ResultDO.PARAM_ERROR);
			result.setErrorMsg("参数错误");
			result.setSuccess(false);
			logger.error("参数错误，手机号码不合法：" + domain.getTelephone());
			return result;
		}

		MCustomerFamilyExample example = new MCustomerFamilyExample();

		Criteria criteria = example.createCriteria();
		criteria.andTelephoneEqualTo(domain.getTelephone());
		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		// 判断手机号除了此客户之外是否重复
		if (!isNumberInValid(domain.getId())) {
			criteria.andCustomerIdNotEqualTo(domain.getId());
		}

		int count = 0;
		try {
			count = customerFamilyMapper.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.FAMILYMEMBER_CHECKTELEPHONE_ERROR);
			result.setErrorMsg("联系人手机号验证失败");
			result.setSuccess(false);
			logger.error("联系人手机号查重，验证失败：" + domain.getTelephone());
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, count);
		return result;
	}

	@Override
	public ResultDO remove(Integer[] ids) {
		ResultDO result = new ResultSupport();
		for (Integer id : ids) {
			ResultDO res = remove(id);
			if (!res.isSuccess()) {
				result.setSuccess(false);
				return result;
			}
		}
		return result;
	}

	@Override
	public ResultDO remove(Integer id) {

		MCustomerFamily entity = new MCustomerFamily();

		ResultSupport result = new ResultSupport();

		if (!result.isSuccess()) {
			result.setErrorMsg("插入客户家庭联系人错误对象复制错误");
			return result;
		}

		entity.setId(id);
		entity.setIsDelete(MemberConstant.DB_ISDEL_YES);

		int ret = -1;

		try {
			ret = customerFamilyMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			ret = -1;
		}

		if (ret < 0) {
			result.setErrorMsg("修改客户家庭联系人错误插入失败");
			result.setSuccess(false);
		}

		return result;
	}

	@Override
	public ResultDO modifi(CustomerFamilyDO domain) {

		MCustomerFamily entity = new MCustomerFamily();
		ResultDO result = BeanUtilsExtends.copy(entity, domain);

		if (!result.isSuccess()) {
			result.setErrorMsg("插入客户家庭联系人错误对象复制错误");
			return result;
		}

		entity.setModifitime(Calendar.getInstance().getTime());
		if (StringUtils.isNotEmpty(domain.getBirthdayStamp())) {
			entity.setBirthday(new Date(Long.parseLong(domain.getBirthdayStamp())));
		}

		int ret = -1;
		try {
			ret = customerFamilyMapper.updateByPrimaryKeySelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			ret = -1;
		}

		if (ret < 0) {
			result.setErrorMsg("修改客户家庭联系人错误插入失败");
			result.setSuccess(false);
		}

		return result;
	}

	@Override
	public ResultDO get(Integer id) {

		ResultDO result = new ResultSupport();

		MCustomerFamily entity = null;

		try {
			entity = customerFamilyMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (entity == null) {
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getCustomerFamilyDO(entity));
		return result;
	}

	@Override
	public ResultDO query(CustomerFamilyQueryDO query) {

		ResultDO result = new ResultSupport();

		List<MCustomerFamily> list = null;

		MCustomerFamilyExample example = new MCustomerFamilyExample();
		Criteria criteria = example.createCriteria();
		if (!isNumberInValid(query.getCustomerId())) {
			criteria.andCustomerIdEqualTo(query.getCustomerId());
		}
		if (query.getIsFirst() != null) {
			criteria.andIsFirstEqualTo(query.getIsFirst());
		}

		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		// 是否进行分页
		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = customerFamilyMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}

		try {
			list = customerFamilyMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, getCustomerFamilyDOList(list));
		return result;
	}

	@Override
	public ResultDO getFirstByCustomerID(Integer id) {

		ResultDO result = new ResultSupport();

		List<MCustomerFamily> list = null;

		MCustomerFamilyExample example = new MCustomerFamilyExample();
		Criteria criteria = example.createCriteria();
		criteria.andCustomerIdEqualTo(id);
		criteria.andIsFirstEqualTo(MemberConstant.FAMILY_IS_FIRST);
		criteria.andIsDeleteEqualTo(MemberConstant.DB_ISDEL_NO);

		try {
			list = customerFamilyMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			return result;
		}
		if (list == null || list.size() < 1) {
			result.setSuccess(false);
			return result;
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, getCustomerFamilyDO(list.get(0)));
		return result;
	}

	/**
	 * 验证手机号
	 *
	 */
	public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(14[5-9]|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8,9])))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	@Override
	public ResultDO update(CustomerFamilyDO domain) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 对象拷贝单个实体到对象中
	 * 
	 * @param obj
	 * @return 返回DO对象
	 */
	public CustomerFamilyDO getCustomerFamilyDO(MCustomerFamily entity) {
		CustomerFamilyDO dst = new CustomerFamilyDO();
		if (entity == null)
			return dst;
		dst = BeanUtilsExtends.copyProperties(dst, entity) ? dst : null;
		if (null != entity.getBirthday()) {
			dst.setBirthdayStamp(entity.getBirthday().getTime() + "");
		}
		dst.setCreateTimeName(entity.getCreatetime().getTime() + "");
		dst.setModifiTimeName(entity.getModifitime().getTime() + "");
		DictionariesDO dic = new DictionariesDO();
		if (null != entity.getRelation()) {
			dic = dicClientAPI.get(entity.getRelation());
			if (dic != null) {
				dst.setRelationName(dic.getDataItem());
			}
		}
		if (null != entity.getWorkDicId()) {
			dic = dicClientAPI.get(entity.getWorkDicId());
			if (dic != null) {
				dst.setWorkName(dic.getDataItem());
			}
		}
		dst.setAge(getAge(entity.getBirthday()));
		if (entity.getGender() == 1) {
			dst.setGenderName("男");
		} else {
			dst.setGenderName("女");
		}
		return dst;
	}

	/**
	 * 对象拷贝多个实体到列表中
	 * 
	 * @param List
	 * @return List
	 */
	public List<CustomerFamilyDO> getCustomerFamilyDOList(List<MCustomerFamily> list) {
		List<CustomerFamilyDO> result = new ArrayList<CustomerFamilyDO>();
		if (list != null && !list.isEmpty()) {
			for (MCustomerFamily entity : list) {
				CustomerFamilyDO domain = getCustomerFamilyDO(entity);
				if (domain != null) {
					result.add(domain);
				}
			}
		}
		return result;
	}

	public int getAge(Date birthday) {
		if (null == birthday) {
			return 0;
		}
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		calendar.setTime(birthday);
		return year - calendar.get(Calendar.YEAR);
	}
}
